
package org.davidliebman.android.awesomecube;

import java.util.ArrayList;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.*;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.content.*;
import android.view.*;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

public class GlCubeActivity extends Activity implements OnGestureListener {

	private CubeGLSurfaceView mSurface;
	private ArrayAdapter<CharSequence> adapter;
	private TextView mMoveOnScreen;
	private View button_view;
	private ImageView mSplash ;
	private Vibrator mVibrate;
	
	private InputQueue<Integer> mInput = new InputQueue<Integer>();
	private ArrayList<String>  mList = new ArrayList<String>();
	private ArrayList<Integer> mEnumeration = new ArrayList<Integer>();
	private ArrayList<String> mShorthand = new ArrayList<String>();
	private String mMoveList = new String("Moves: ");
	private ScrambleCube mScramble = new ScrambleCube();
	private GestureDetector mGestureDetector;
	
	private int mOptionChosen = 0;
	
	private int mLeft, mRight, mTop, mBot;
	public static final int TILT_RIGHT = 0;
	public static final int TILT_LEFT = 1;
	public static final int TILT_UP = 2;
	public static final int TILT_DOWN = 3;
	
	public static final String KEY_START  = new String("CUBE_KEY_");
	
	public static final int DIALOG_SCRAMBLE_ID = 0;
	public static final int DIALOG_SHOW_SOLVED = 1;
	
	public boolean mDisplayAtAngle = false;
	public boolean mUseMirror = true;
	public boolean mAnimate = true;
	public boolean mForceState = false;
	public boolean mForceScramble = false;
	public Handler mHandler;
	
	private static final int SWIPE_MIN_DISTANCE = 20;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 20;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.main);
		mSplash = (ImageView) findViewById(R.id.splashscreen);
		mVibrate = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
		
		mSurface = (CubeGLSurfaceView) this.findViewById(R.id.mainsurfaceview);
		
		mSurface.mArray.setQueue(mInput);
		mSurface.mArray.setRenderer(mSurface.renderer);
		
		SharedPreferences preferences = getSharedPreferences(CubeOptionsActivity.AWESOME_NAME, MODE_PRIVATE);
		mDisplayAtAngle = preferences.getBoolean(CubeOptionsActivity.SAVED_DISPLAY_ANGLE, false);
		mUseMirror = preferences.getBoolean(CubeOptionsActivity.SAVED_USE_MIRROR, true);
        mAnimate = preferences.getBoolean(CubeOptionsActivity.SAVED_PLAY_ANIMATION, false);
		
		mSurface.mArray.renderer.setUseDisplayAtAngle(mDisplayAtAngle);
		mSurface.mArray.renderer.setUseMirror(mUseMirror);
		
		
		mGestureDetector = new GestureDetector (this,this) ;
		
        final Spinner spinner = (Spinner) findViewById(R.id.movespinner);
		
        buildSpinnerList();
        
        
        mMoveOnScreen = (TextView) findViewById(R.id.movelist);
        mMoveOnScreen.setText(mMoveList);
        
		adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, mList.toArray());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(
                new OnItemSelectedListener() {
                    public void onItemSelected(
                            AdapterView<?> parent, View view, int position, long id) {
                    	
                    	
                    	mOptionChosen = mEnumeration.get(position);
                    	//NOTE: add code for blinking arrow in 45 deg angle mode
                    	mSurface.mArray.renderer.setChosenMove(mOptionChosen);
                    }

                    public void onNothingSelected(AdapterView<?> parent) {
                    	//
                    }
                });


        
        
        /* invisible button */
        button_view = (View) findViewById(R.id.mainsurfaceview);
        
	    button_view.setOnTouchListener( new OnTouchListener () {
	    	
	    	
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				boolean mReturnValue = true;
				int [] locationXY = new int[2];
				button_view.getLocationInWindow(locationXY);
				mLeft = 0;
				mRight = button_view.getWidth();
				mTop = 0; 
				mBot = button_view.getHeight();
					
				if(mGestureDetector.onTouchEvent(event)) {
					mReturnValue = true;
				}

				
				if( ! mDisplayAtAngle ) { 
					if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
						Positioning mP = new Positioning();
			        	mP = getTiltFromTouch((int)event.getX(),(int) event.getY());
			        	mSurface.mArray.renderer.setTilt(mP);
			        	mReturnValue = true;
					}
					else if (event.getAction() == MotionEvent.ACTION_UP) {
						Positioning mP = new Positioning();
			        	mSurface.mArray.renderer.setTilt(mP);
			        	mReturnValue = true;
					}
				}
				else {// remove if true
					if (event.getAction() ==  MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE) {
						
						PointXYZ in = new PointXYZ(event.getRawX(), (mBot + locationXY[1] ) - event.getRawY(), 0);
						mSurface.renderer.setPointAndHandler(in,  mHandler);
						mReturnValue = true;
						//Log.e("coordinate","mBot: " + mBot + "  locationXY[1]:" + locationXY[1] + " total:" + ((mBot + locationXY[1]) -event.getRawY() ) + " <--------");
						
					}
					else if (event.getAction()  ==  MotionEvent.ACTION_UP) {
						PointXYZ in = new PointXYZ(0,0,0);
						
						//out = mPick.getWorldCoords(in, mRight, mBot);
						mSurface.renderer.setPointAndHandler(in,  mHandler);
						mReturnValue = true;
					}
					
				}
				
				return mReturnValue; // true
			}
	        
	    });
	    
		

		
		/* button at bottom of view */
	    final Button gobutton = (Button) findViewById(R.id.gobutton);
	    gobutton.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        		        	
	        	if (mEnumeration.get(mOptionChosen) != OrientationArray.MOVE_NONE &&
	        			mEnumeration.get(mOptionChosen) != OrientationArray.GO_OPTIONS) {
	        		mInput.add(mEnumeration.get(mOptionChosen));

	        		
	        		mMoveList = mMoveList + " " + mShorthand.get(mOptionChosen) + ",";
	        		Toast.makeText(GlCubeActivity.this,  mMoveList, Toast.LENGTH_SHORT).show();
		        	mMoveOnScreen.setText(mMoveList);
	        		
	        	}
	        	else if (mEnumeration.get(mOptionChosen) == OrientationArray.GO_OPTIONS){
	        		Intent StartOptionIntent = new Intent(GlCubeActivity.this, CubeOptionsActivity.class);
	        		startActivity(StartOptionIntent);
	        	}
	        	
	        }
	    });
		
        mSurface.renderer.setAnimate(preferences.getBoolean(CubeOptionsActivity.SAVED_PLAY_ANIMATION, false));

        mHandler = new Handler() {
        	
        	
        	public void handleMessage(Message msg) {
        		boolean mFound = false;
        		int mPosition = 0;
        		for(int i = 0; i < mList.size(); i ++) {
        			if( mEnumeration.get(i) == msg.what) {
        				mPosition = i;
        				mFound = true;
        			}
        		}
        		if (mFound) {
        			spinner.setSelection(mPosition);
        		}
        		
        		else if (msg.what == OrientationArray.SHOW_SOLVED) {
        			// show solved dialog.
        			showDialog(DIALOG_SHOW_SOLVED);
        		}
        		
        		else if (msg.what == OrientationArray.SHOW_SPLASH) {
        			mSplash.setVisibility(View.VISIBLE);

        			Animation myFadeInAnimation = AnimationUtils.loadAnimation(GlCubeActivity.this, R.anim.fadein);
        			mSplash.startAnimation(myFadeInAnimation); 
        		}
        		
        		else if (msg.what == OrientationArray.SHOW_NOSPLASH) {
        			mSplash.setVisibility(View.GONE);
        		}

        		super.handleMessage(msg);
        		
        	}
        
        };
        
		mSurface.mArray.setHandler(mHandler);

	}
	
	
	@Override 
	public boolean dispatchTouchEvent(MotionEvent ev){

	    mGestureDetector.onTouchEvent(ev);
	    super.dispatchTouchEvent(ev); 
	    return true;
	} 
	
	@Override 
	public boolean onTouchEvent(MotionEvent event) {
		boolean mReturnValue = false;
		
		if ( mGestureDetector.onTouchEvent(event)) {
			mReturnValue = true;
		}

	
		super.onTouchEvent(event);
		return true;
	}
	
	
	
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		try {
		
			if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
				mInput.add(OrientationArray.MOVE_Y_CW);
        		mMoveList = mMoveList + " "  + "Y,"; // must get shorthand right.
	        	mMoveOnScreen.setText(mMoveList);


			} 
			else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
				mInput.add(OrientationArray.MOVE_Y_CCW);
        		mMoveList = mMoveList + " " +  "Y',"; // must get shorthand right.
	        	mMoveOnScreen.setText(mMoveList);

			}
		} 
		catch (Exception e) {
			//...
		}
		return true;
	}

	@Override
	public void onWindowFocusChanged(boolean mHasFocus) {
		//if (!mHasFocus) this.setPreferencesFromTileFaces();
		super.onWindowFocusChanged(mHasFocus);
	}
	
	@Override
	public void onResume() {
		this.measureDisplay();
		
		SharedPreferences preferences = getSharedPreferences(CubeOptionsActivity.AWESOME_NAME, MODE_PRIVATE);
        mSurface.renderer.setAnimate(preferences.getBoolean(CubeOptionsActivity.SAVED_PLAY_ANIMATION, false));
		
		mSplash = (ImageView) findViewById(R.id.splashscreen);
		showSplashScreen();
		
        this.setTileFacesFromPreferences();
        
		super.onResume();
	}
	
	@Override
	public void onPause() {
		this.setPreferencesFromTileFaces();
		super.onPause();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.main_menu, menu);
	    
	    return true;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		
		if (this.mDisplayAtAngle) {
	    	menu.findItem(R.id.menu_mirror_item).setVisible(false);
	    }
		else {
			menu.findItem(R.id.menu_mirror_item).setVisible(true);
		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean mReturnValue = false;
		boolean mRunResumeCode = false;
		SharedPreferences preferences = getSharedPreferences(CubeOptionsActivity.AWESOME_NAME, MODE_PRIVATE);
		SharedPreferences.Editor mE = preferences.edit();

	    switch (item.getItemId()) {
	    case R.id.menu_yes_animation_item:
	        
	    	mAnimate = true;
	        mE.putBoolean(CubeOptionsActivity.SAVED_PLAY_ANIMATION, mAnimate);
	        mSurface.renderer.setAnimate(mAnimate);
	    	mReturnValue = true;
	    	break;
	        
	    case R.id.menu_no_animation_item:
	    	
	    	mAnimate = false;
	        mE.putBoolean(CubeOptionsActivity.SAVED_PLAY_ANIMATION, mAnimate);
	        mSurface.renderer.setAnimate(mAnimate);
	    	mReturnValue = true;
	    	break;
	    case R.id.menu_cube_angle_item:
	    	this.mDisplayAtAngle = ! this.mDisplayAtAngle;
			mSurface.mArray.renderer.setUseDisplayAtAngle(mDisplayAtAngle);
        	mSurface.mArray.renderer.setDisplayAngleFromMenu();
        	mE.putBoolean(CubeOptionsActivity.SAVED_DISPLAY_ANGLE, mDisplayAtAngle);
	        mReturnValue = true;
	        break;
        	//return true;
	    case R.id.menu_cube_saved_saved:
    		mE.putInt(CubeOptionsActivity.SAVED_SCRAMBLE_CUBE, CubeOptionsActivity.STATE_SAVED);
    		mRunResumeCode = false;
	    	this.setPreferencesFromTileFaces();
	    	mReturnValue = true;
	        break;
	    	
	    case R.id.menu_cube_saved_scramble:
	    	
    		this.mSurface.mArray.wipeTiles();
    		this.mSurface.renderer.mPieces.wipeTiles();
    		mMoveList = new String("Moves: ");
        	mMoveOnScreen.setText(mMoveList);
    		mE.putInt(CubeOptionsActivity.SAVED_SCRAMBLE_CUBE, CubeOptionsActivity.STATE_SCRAMBLE);
    		mE.commit();
    		this.mForceState = true;
    		this.mForceScramble = true;
    		this.setTileFacesFromPreferences();
    		this.setPreferencesFromTileFaces();

    		mRunResumeCode = true;
	    	
	    	mReturnValue = true;
	        break;
	    	
	    	
	    case R.id.menu_cube_saved_solved:
	    	
    		this.mSurface.mArray.wipeTiles();
    		this.mSurface.renderer.mPieces.wipeTiles();
    		mMoveList = new String("Moves: ");
        	mMoveOnScreen.setText(mMoveList);
    		mE.putInt(CubeOptionsActivity.SAVED_SCRAMBLE_CUBE, CubeOptionsActivity.STATE_SAVED);
    		mE.commit();
    		
    		this.mForceState = true;
    		this.setPreferencesFromTileFaces();
    		mRunResumeCode = true;
	    	//this.setTileFacesFromPreferences();
	    	mReturnValue = true;
	    	break;
	    	//return true;
	    case R.id.menu_movelist_clear_item:
	    	mMoveList = new String("Recent: ");
			mMoveOnScreen.setText(mMoveList);
			
	    	mReturnValue = true;
	    	break;
	    	
	    case R.id.menu_mirror_clear_item:
	    	mUseMirror = false;
			mSurface.mArray.renderer.setUseMirror(mUseMirror);
	        mE.putBoolean(CubeOptionsActivity.SAVED_USE_MIRROR, mUseMirror);

	    	mReturnValue = true;
	    	break;
	    	
	    case R.id.menu_mirror_show_item:
	    	mUseMirror = true;
			mSurface.mArray.renderer.setUseMirror(mUseMirror);
	        mE.putBoolean(CubeOptionsActivity.SAVED_USE_MIRROR, mUseMirror);

	    	mReturnValue = true;
	    	break;
	    	
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	    
	    mE.commit();
	    if (mRunResumeCode) this.setTileFacesFromPreferences();
	    mRunResumeCode = false;
	    return mReturnValue;
	}
	
	public void measureDisplay() {
		int mTotWidgetHeight = 0;// ((Button)this.findViewById(R.id.gobutton)).getHeight() * 2;
		//Log.e("Activity","widget " + mTotWidgetHeight);
		Display display = ((WindowManager) 
				getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		this.mSurface.renderer.setScreenDimensions(display.getWidth(), display.getHeight() - mTotWidgetHeight);
	}
	
	public void buildSpinnerList() {
		mList.clear();
		mEnumeration.clear();
		mShorthand.clear();
		this.addSpinnerEntry("No Move", OrientationArray.MOVE_NONE, "none");
		this.addSpinnerEntry("Front Clockwise", OrientationArray.MOVE_F_CW, "F");
		this.addSpinnerEntry("Front Counter-Clockwise", OrientationArray.MOVE_F_CCW, "F'");
		this.addSpinnerEntry("Back Clockwise", OrientationArray.MOVE_B_CW, "B");
		this.addSpinnerEntry("Back Counter-Clockwise", OrientationArray.MOVE_B_CCW, "B'");
		this.addSpinnerEntry("Up Clockwise", OrientationArray.MOVE_U_CW, "U");
		this.addSpinnerEntry("Up Counter-Clockwise", OrientationArray.MOVE_U_CCW, "U'");
		this.addSpinnerEntry("Down Clockwise", OrientationArray.MOVE_D_CW, "D");
		this.addSpinnerEntry("Down Counter-Clockwise", OrientationArray.MOVE_D_CCW, "D'");
		this.addSpinnerEntry("Left Clockwise", OrientationArray.MOVE_L_CW, "L");
		this.addSpinnerEntry("Left Counter-Clockwise", OrientationArray.MOVE_L_CCW, "L'");
		this.addSpinnerEntry("Right Clockwise", OrientationArray.MOVE_R_CW, "R");
		this.addSpinnerEntry("Right Counter-Clockwise", OrientationArray.MOVE_R_CCW, "R'");
		this.addSpinnerEntry("X Axis Clockwise", OrientationArray.MOVE_X_CW, "X");
		this.addSpinnerEntry("X Axis Counter-Clockwise", OrientationArray.MOVE_X_CCW,  "X'");
		this.addSpinnerEntry("Y Axis Clockwise", OrientationArray.MOVE_Y_CW, "Y");
		this.addSpinnerEntry("Y Axis Counter-Clockwise", OrientationArray.MOVE_Y_CCW, "Y'");
		this.addSpinnerEntry("Z Axis Clockwise", OrientationArray.MOVE_Z_CW, "Z");
		this.addSpinnerEntry("Z Axis Counter-Clockwise", OrientationArray.MOVE_Z_CCW, "Z'");
		this.addSpinnerEntry("Options", OrientationArray.GO_OPTIONS, "none");
	}
	
	public void addSpinnerEntry(String mString, int mNumber, String mShort) {
		mList.add(mString);
		mEnumeration.add(mNumber);
		mShorthand.add(mShort);
	}
	
	public Positioning getTiltFromTouch(int mX, int mY) {
		Positioning mP = new Positioning();
		
		if (this.mDisplayAtAngle) return mP;
		
		int mStandardTilt = 20;
		int mQuarterH = (mRight - mLeft) / 4;
		int mQuarterV = (mBot - mTop) / 4;
		
		if ( mX < mQuarterH) {
			mP.ry =  - mStandardTilt;
		}
		else if ( mX > mQuarterH * 3) {
			mP.ry =  mStandardTilt;
		}
		
		if (mY < mQuarterV) {
			mP.rx =  - mStandardTilt;
		}
		else if (mY > mQuarterV * 3) {
			mP.rx =  mStandardTilt;
		}
		return mP;
	}
	
	
    public void setPreferencesFromTileFaces() {

		SharedPreferences preferences = getSharedPreferences(CubeOptionsActivity.AWESOME_NAME, MODE_PRIVATE);
		
		if( 	preferences.getInt(CubeOptionsActivity.SAVED_SCRAMBLE_CUBE, 
				CubeOptionsActivity.STATE_SAVED) == 
				CubeOptionsActivity.STATE_SAVED || mForceState == true) {
    	
			SharedPreferences.Editor mE = preferences.edit();
			
	    	int[] temp = new int[6*3*3];
	    	for (int j =0; j < 6; j ++) {
	    		for (int x = 0; x < 3; x ++ ) {
	    			for (int y = 0; y < 3; y ++) {
	    				mE.putInt(this.keyFactory( (j * 9) + (x * 3) + y ), 
	    						this.mSurface.mArray.mTile[j][x][y]);
	    			}
	    		}
	    	}
	    	mE.putString(CubeOptionsActivity.SAVED_BREADCRUMBS, mMoveList);
	    	mE.commit();
		}
		mForceState = false;
    }
	
	
	
	public void setTileFacesFromPreferences() {
		    	
		SharedPreferences preferences = getSharedPreferences(CubeOptionsActivity.AWESOME_NAME, MODE_PRIVATE);
		mDisplayAtAngle = preferences.getBoolean(CubeOptionsActivity.SAVED_DISPLAY_ANGLE, false);
		mUseMirror = preferences.getBoolean(CubeOptionsActivity.SAVED_USE_MIRROR, true);
        mAnimate = preferences.getBoolean(CubeOptionsActivity.SAVED_PLAY_ANIMATION, false);
		
		if( 	preferences.getInt(CubeOptionsActivity.SAVED_SCRAMBLE_CUBE, 
				CubeOptionsActivity.STATE_SAVED) == 
				CubeOptionsActivity.STATE_SAVED || mForceState == true) {
			
			this.mMoveList = preferences.getString(CubeOptionsActivity.SAVED_BREADCRUMBS, "Moves: ");
			this.mMoveOnScreen.setText(mMoveList);
			
    		for (int j =0; j < 6; j ++) {
        		for (int x = 0; x < 3; x ++ ) {
        			for (int y = 0; y < 3; y ++) {
        				this.mSurface.mArray.mTile[j][x][y] = preferences.getInt(this.keyFactory( (j * 9) + (x * 3) + y ), 
        						mSurface.mArray.getColorFromKey(j));

        			}
        		}
        	}
    	
		}
		if (preferences.getInt(CubeOptionsActivity.SAVED_SCRAMBLE_CUBE, 
				CubeOptionsActivity.STATE_SAVED) == 
				CubeOptionsActivity.STATE_SCRAMBLE || mForceScramble == true) {
			
			this.scrambleCube();
			
		
		}
		if (preferences.getBoolean(CubeOptionsActivity.SAVED_CLEAR_BREADCRUMBS, 
				false) == true) {
			mMoveList = new String("Recent: ");
			mMoveOnScreen.setText(mMoveList);
			
		}
		
		SharedPreferences.Editor mE = preferences.edit();
		mE.putInt(CubeOptionsActivity.SAVED_SCRAMBLE_CUBE, 
				CubeOptionsActivity.STATE_SAVED);
		mE.putBoolean(CubeOptionsActivity.SAVED_CLEAR_BREADCRUMBS, false);
		mE.commit();
		mForceState = false;
    	mForceScramble = false;
	}
	
	public String keyFactory(int n) {
		return new String(KEY_START + n);
	}
	
	protected Dialog onCreateDialog(int id) {
	    Dialog dialog;
	    AlertDialog.Builder builder;
    	AlertDialog alertDialog;

    	Context mContext = getApplicationContext();
    	LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    	View layout;
    	TextView text;
    	ImageView image;
    	String mPositive, mNegative;
    	
	    switch(id) {
	    case DIALOG_SCRAMBLE_ID:
	    	
	    	layout = inflater.inflate(R.layout.congrats,
	    			(ViewGroup) findViewById(R.id.layout_root));
	    	String mDialogText = new String( "These are the moves that were used to scramble the cube: " + 
	    			mScramble.getString() );
	    	text = (TextView) layout.findViewById(R.id.congrats_text);
	    	text.setText(mDialogText);
	    	
	    	image = (ImageView) layout.findViewById(R.id.image);
	    	image.setImageResource(R.drawable.bigsmilered);
	    	mPositive = new String("Work On Cube.");
   	    	mNegative = new String("Manage Options.");
	    	builder = new AlertDialog.Builder(this);
	    	builder.setView(layout);
	    	builder.setCancelable(false)
    	       .setPositiveButton(mPositive, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	  
    	        	   dialog.cancel();
    	        	   removeDialog(DIALOG_SCRAMBLE_ID);
    	        	   
    	           }
    	       })
    	       .setNegativeButton(mNegative, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   	Intent MenuIntent = new Intent(GlCubeActivity.this, CubeOptionsActivity.class);
    	        		startActivity(MenuIntent);
    	                dialog.cancel();
    	                removeDialog(DIALOG_SCRAMBLE_ID);
    	           }
    	       });
	    	
	    	alertDialog = builder.create();
	    	
	    	dialog = (Dialog) alertDialog;
	    	
	    	break;
	    //////////////////////////////
	    case DIALOG_SHOW_SOLVED:
	    	
	    	layout = inflater.inflate(R.layout.congrats,
	    			(ViewGroup) findViewById(R.id.layout_root));
	    	text = (TextView) layout.findViewById(R.id.congrats_text);
	    	text.setText("The Cube is solved!!" );
	    	image = (ImageView) layout.findViewById(R.id.image);
	    	image.setImageResource(R.drawable.bigsmilered);
	    	mPositive = new String("Work On Cube.");
   	    	mNegative = new String("Manage Options.");
	    	builder = new AlertDialog.Builder(this);
	    	builder.setView(layout);
	    	builder.setCancelable(false)
    	       .setPositiveButton(mPositive, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	  
    	        	   dialog.cancel();
    	        	   
    	           }
    	       })
    	       .setNegativeButton(mNegative, new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	        	   	Intent MenuIntent = new Intent(GlCubeActivity.this, CubeOptionsActivity.class);
    	        		startActivity(MenuIntent);
    	                dialog.cancel();
    	           }
    	       });
	    	
	    	alertDialog = builder.create();
	    	
	    	dialog = (Dialog) alertDialog;
	    	
	    	break;
	    ////////////////////////////////
	    default:
	        dialog = null;
	    }
	    return dialog;
	}

	public void showSplashScreen() {
		mSplash.setVisibility(View.VISIBLE);

		
		new Thread(new Runnable() {
		    public void run() {
		    	
		    	
		    	mHandler.sendEmptyMessage(OrientationArray.SHOW_SPLASH);
		    	
				try{
					Thread.currentThread().sleep(3500);
					mHandler.sendEmptyMessage(OrientationArray.SHOW_NOSPLASH);
					//mVibrate.vibrate(330);
				}
				catch (InterruptedException e) {
					
					//mSplash.setVisibility(View.GONE);
					mHandler.sendEmptyMessage(OrientationArray.SHOW_NOSPLASH);
				}
		    }
		  }).start();

		
	}
	
	public void scrambleCube() {
		this.mSurface.mArray.wipeTiles();
		this.mSurface.renderer.mPieces.wipeTiles();
		mScramble = new ScrambleCube();
		mInput = new InputQueue<Integer>();
		mInput = mScramble.getQueue();
		mSurface.mArray.setQueue(mInput);
		this.showDialog(DIALOG_SCRAMBLE_ID);
	}
	
	/* Overrides and Helper methods */

	@Override
	public boolean onScroll(MotionEvent ev1, MotionEvent ev2, float velocityX, float velocityY) {
		return false;
	}
	
	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		
	}

	@Override
	public void onShowPress(MotionEvent e) {
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

}